<template>
  <div>
    <Navbar
      :appTitle="appTitle"
      :rname="appTitle == '新建移仓单' ? 'scan' : ''"
      @ClickRight="clickCode('', '', 'batch')"
    />
    <div
      class="form-content wrap-apply"
      :style="{
        top: GLOBAL.currentEnvironment ? '0' : '',
        height: GLOBAL.currentEnvironment ? '100vh' : 'calc(100vh - 100px)',
        paddingBottom: GLOBAL.currentEnvironment ? '120px' : '',
      }"
    >
      <van-cell-group class="formItemFlex">
        <p class="label required FormTit"><span></span>移仓单编号</p>
        <div class="haveUnitBox">
          <van-field
            v-model="buildForm.code"
            :maxLength="50"
            placeholder="请输入、不输入则自动生成"
            input-align="right"
          />
        </div>
      </van-cell-group>
      <div class="bottomLine"></div>
      <van-cell-group class="formItemFlex">
        <p class="label required FormTit"><span></span>单据日期</p>
        <van-field
          input-align="right"
          is-link
          readonly
          name="picker"
          v-model="buildForm.docDate"
          @click="openTimePicker(i, buildForm.docDate)"
          placeholder="请选择"
        />
        <div class="bottomLine"></div>
      </van-cell-group>

      <div class="list">
        <div
          class="wrap"
          v-for="(p, i) in entryDetails"
          :key="p.id"
          v-show="entryDetails.length != 0"
          style="margin-bottom: 10px;"
        >
          <van-cell-group>
            <p class="label otherText">
              <span>移仓明细（{{ i + 1 }}）</span>
              <span class="deleteStyle" @click="deleteGoods(i)">删除</span>
            </p>
            <div class="bottomLine"></div>
            <div class="top">
              <div class="icon"></div>
              <div class="title titleWidth">
                {{ p.goodsCode }}| {{ p.goodsName }}| {{ p.spec }}
              </div>
            </div>
            <div class="center">
              <div>
                <p>
                  <span class="key">包装规格：</span>
                  <span class="value">{{ p.packageSpec }}</span>
                </p>
                <p>
                  <span class="key">产地：</span>
                  <span class="value">{{ p.address }}</span>
                </p>
                <p class="label-list">
                  <span>{{ p.produceDate }}</span>
                  <span>{{ p.batchCode }}</span>
                  <span>{{ p.unitName }}</span>
                </p>
              </div>
            </div>

            <van-cell-group class="formItemFlex">
              <p class="label required FormTit"><span></span>移出库位</p>
              <div class="haveUnitBox">
                <van-field
                  style="width: 6.6rem"
                  v-model="p.latticeOutInfo"
                  placeholder="请选择或扫码"
                  input-align="right"
                  readOnly
                  @click="showLatticeNotification(i, p, 'out')"
                >
                  <template #right-icon>
                    <div style="display: flex;">
                      <van-icon
                        @click="showLatticeNotification(i, p, 'out')"
                        size="20"
                        color="#999"
                        name="arrow"
                        style="margin-top: 2px"
                      />
                      <van-icon
                        @click.stop="clickCode(i, p, 'out')"
                        size="20"
                        color="#999"
                        name="scan"
                        style="margin-top: 2px"
                      />
                    </div>
                  </template>
                </van-field>
              </div>
            </van-cell-group>
            <div class="bottomLine"></div>
            <van-cell-group class="formItemFlex">
              <p class="label required FormTit"><span></span>移入库位</p>
              <div class="haveUnitBox">
                <van-field
                  style="width: 6.6rem"
                  v-model="p.latticeInfo"
                  placeholder="请选择或扫码"
                  input-align="right"
                  readOnly
                  @click="showLatticeNotification(i, p, 'in')"
                >
                  <template #right-icon>
                    <div style="display: flex;">
                      <van-icon
                        @click="showLatticeNotification(i, p, 'in')"
                        size="20"
                        color="#999"
                        name="arrow"
                        style="margin-top: 2px"
                      />
                      <van-icon
                        @click.stop="clickCode(i, p, 'in')"
                        size="20"
                        color="#999"
                        name="scan"
                        style="margin-top: 2px"
                      />
                    </div>
                  </template>
                </van-field>
              </div>
            </van-cell-group>
            <div class="bottomLine"></div>
            <van-cell-group class="formItemFlex">
              <p class="label required FormTit"><span></span>数量</p>
              <div class="haveUnitBox">
                <van-field
                  v-model="p.goodsNum"
                  type="number"
                  placeholder="请输入"
                  input-align="right"
                  :formatter="(e) => needInNumChange(e, p)"
                />
              </div>
            </van-cell-group>
          </van-cell-group>
        </div>

        <div class="addGoodScontain">
          <div class="addgoods" @click="addInventoryGoods">
            <van-icon
              name="plus"
              size="16px"
              color="#1890ff"
              style="top: 2px"
            />
            <a>物品</a>
          </div>
        </div>
      </div>

      <div class="search-bottoms">
        <van-button  :loading="subLoading" loading-text="提交中..." class="btnconfirm" @click="btnConfirm">提交</van-button >
      </div>
    </div>
    <!--选择物品 -->
    <goods-pickers-ak
      v-if="showGoodsPicker"
      :listUrl="listUrl"
      :columns="goodsColumns"
      :selectedGoods="[]"
      @getCheckedGoods="getCheckedGoods"
    ></goods-pickers-ak>
    <!--选择日期 -->
    <van-popup v-model="timePickShow" position="bottom">
      <van-datetime-picker
        @confirm="confirmPick"
        v-model="happenTime"
        @cancel="cancelPick"
        type="date"
        title="单据日期"
        :formatter="formatter"
      />
    </van-popup>
    <!--选择移入库位 -->
    <binLocation-pickers-ak
      v-if="isShowInLattice"
      :listUrl="latticeNotificationInUrl"
      :columns="latticeInColumns"
      :checkedShow="recentLatIndex == -1 ? true : false"
      :selectedGoods="
        recentLatIndex == -1
          ? entryDetails[recentGoodsIndex]['inLatticeDtoList']
          : []
      "
      @getCheckedValue="getCheckedValue"
      @handleList="handleList"
    ></binLocation-pickers-ak>
    <!--选择移出库位 -->
    <binLocation-pickers-ak
      v-if="isShowOutLattice"
      :listUrl="latticeNotificationOutUrl"
      :columns="latticeOutColumns"
      :checkedShow="recentLatIndex == -1 ? true : false"
      :selectedGoods="
        recentLatIndex == -1
          ? entryDetails[recentGoodsIndex]['inLatticeDtoList']
          : []
      "
      @handleList="handleOutList"
    ></binLocation-pickers-ak>
    <!-- 浏览器扫码组件 -->
    <qrcode
      :qrcode="codeForm.qrcode"
      :showClose="codeForm.showClose"
      v-show="codeForm.qrcode"
      :camera="camera"
      :torchActive="torchActive"
      @switchCamera="switchCamera"
      @ClickFlash="ClickFlash"
      @turnCameraOff="turnCameraOff"
      @onDecode="onDecode"
      @onInit="onInit"
    />
    <!-- 激光扫码组件 -->
    <PDAsao ref="pda" @changeScan="changeScan" />
    <!--选择移出库位物品   注意！！remove为true,跳转到物品页面，列表数据不需要请求，数据为goodsRemoveData-->
    <goods-pickers-ak
      v-if="showGoodsRemovePicker"
      :columns="goodsRemoveColumns"
      :selectedGoods="[]"
      :remove="true"
      :goodsRemoveData="goodsRemoveData"
      :goodsRemoveLattice="goodsRemoveLattice"
      @getCheckedGoods="getCheckedGoodsRemove"
    ></goods-pickers-ak>
  </div>
</template>
<script>
import moment from "moment";
import Navbar from "@/components/navBar/navBar_right";
import VanFieldSelectPicker from "@/components/ActionSheet/VanFieldSelectPicker";
import GoodsPickersAk from "@/components/choiceuse/GoodsPickersAk";
import {
  genEntityCode,
  getDictItemsByTypes,
  inboundTaskEdit,
  getBathRelProductDate,
  inboundTaskDetail,
  inboundTaskDetailGoodsList,
  getWarehouseLatticeDetail,
  queryBasicInfoById,
  queryInGoodsInfoPage,
} from "@/api/inventoryOrder";
import {
  getLatticeNotificationForOutBound,
  shiftAdd,
  getLatticeInfoForScan,
} from "@/api/removeAndinventory";
import store from "@/store";
import BinLocationPickersAk from "@/components/choiceuse/BinLocationPickersAk";
import PDAsao from "@/components/scanCode/PDAsao.vue";

let recTime = moment(new Date()).format("YYYY-MM-DD");
export default {
  name: "warehousingTaskForm",
  components: {
    Navbar,
    VanFieldSelectPicker,
    GoodsPickersAk,
    BinLocationPickersAk,
    qrcode: () => import("@/components/scanCode"),
    PDAsao,
  },
  data() {
    return {
      recTime,
      appTitle: "新建移仓单",
      buildForm: {
        code: "",
      },
      subLoading: false,
      showGoodsPicker: false,
      listUrl: "/wmsgoodsnotification/getOutboundOrderNotification",
      goodsColumns: {
        titleKey: ["goodsCode", "goodsName", "spec"], //标题
        content: [
          //内容
          {
            name: "包装规格",
            key: ["packageSpec"],
          },
          {
            name: "产地",
            key: ["address"],
          },
          {
            name: "库存数量",
            key: ["goodsNumTxt"],
          },
        ],
        labelKey: ["produceDate", "batchCode", "unitName"],
        operationText: "",
      },
      goodsRemoveColumns: {
        titleKey: ["goodsCode", "goodsName", "spec"], //标题
        content: [
          //内容
          {
            name: "产地",
            key: ["address"],
          },
          {
            name: "包装规格",
            key: ["packageSpec"],
          },
        ],
        labelKey: ["produceDate", "batchCode", "unitName"],
        operationText: "",
      },
      latticeNotificationInUrl: "/wmslattice/getLatticeNotification", //移入库位的url
      // 移入库位
      latticeInColumns: {
        titleKey: ["latticeCode", "latticeName"], //标题
        content: [
          //内容
          {
            name: "库位库存",
            key: ["goodsNumTxt"],
          },
        ],
        labelKey: [], //标签
        operationText: "",
      },
      latticeOutColumns: {
        titleKey: ["latticeCode", "latticeName"], //标题
        content: [
          //内容
          {
            name: "库位库存",
            key: ["goodsNumText"],
          },
        ],
        labelKey: [], //标签
        operationText: "",
      },
      latticeNotificationOutUrl:
        "/wmslattice/getLatticeNotificationForOutBound", //移出库位的url

      entryDetails: [],
      recentGoodsIndex: "",
      warehousingTypes: [],
      timePickShow: false,
      happenTime: "",
      taskId: "",
      isEdit: false,
      isShowInLattice: false,
      isShowOutLattice: false,
      camera: "off",
      // 扫码相关
      codeForm: {
        qrcode: false,
        showClose: false,
      },
      torchActive: true,
      recentGoodsIndex: 0,
      recentLatIndex: 0,
      goodParam: {},
      showGoodsRemovePicker: false,
      goodsRemoveLattice: {},
      goodsRemoveData: [],
    };
  },
  beforeRouteLeave(to, from, next) {
    if (this.showGoodsPicker || this.isShowInLattice || this.isShowOutLattice) {
      this.showGoodsPicker = false;
      this.isShowInLattice = false;
      this.isShowOutLattice = false;
      this.appTitle = "新建移仓单";
      next(false);
    } else {
      next();
    }
  },
  async created() {
    store.commit("SET_CURRENT_PREFIX", "/jksaas-produce/produce");
    this.initData();
  },
  methods: {
    // 重置form表单
    resetForm () {
      this.buildForm = {
        code: "",
      }

      this.entryDetails = []
      this.recentGoodsIndex = ''
      this.warehousingTypes = []

      this.timePickShow = false
      this.happenTime = ''
      this.taskId = ''

      this.isEdit = false
      this.isShowInLattice = false
      this.isShowOutLattice = false

      this.torchActive = true
      this.recentGoodsIndex = 0
      this.recentLatIndex = 0

      this.goodParam = {}
      this.showGoodsRemovePicker = false
      this.goodsRemoveLattice = {}
      this.goodsRemoveData = []
    },
    // 提交
    btnConfirm() {
      if (!this.buildForm.code) {
        this.$toast(`请输入移仓单编号`);
        return;
      }

      if (!this.buildForm.docDate) {
        this.$toast(`请选择时间`);
        return;
      }

      let isValidated = true;
      try {
        // 入库移仓明细 为空 选项名称、数量 表单验证
        if (this.entryDetails && this.entryDetails.length > 0) {
          this.entryDetails.forEach((element, index) => {
            if (element.goodsId) {
              if (!element.outLatticeId || element.outLatticeId == "") {
                isValidated = false;
                throw new Error(`移仓明细（${index + 1}）移出库位不可为空`);
              }
              if (!element.inLatticeId || element.inLatticeId == "") {
                isValidated = false;
                throw new Error(`移仓明细（${index + 1}）移入库位不可为空`);
              }
              if (
                !element.goodsNum ||
                element.goodsNum == "" ||
                element.goodsNum == 0
              ) {
                isValidated = false;
                throw new Error(`移仓明细（${index + 1}）数量不可为空且不为零`);
              }
            } else {
              isValidated = false;
              throw new Error(`请选择物品`);
            }
          });
          this.handleSubmit();
          return;
          let duplicateindex = this.hasDuplicateObjects(this.entryDetails);
          if (duplicateindex != -1) {
            throw new Error(
              `移仓明细（${duplicateindex +
                1}）移入库位、移出库位不可同时相同！`
            );
          }
        } else {
          isValidated = false;
          throw new Error(`请选择物品`);
        }

        if (!isValidated) {
          return;
        }
      } catch (error) {
        this.$toast(error.message);
        return false;
      }
      this.handleSubmit();
    },
    handleSubmit() {
      let params = {
        ...this.buildForm,
        shiftDetailSaveAndUpdateDtoList: this.entryDetails.map((item) => {
          return {
            outLatticeId: item.outLatticeId,
            outLatticeGoodsNum: item.outLatticeGoodsNum,
            inLatticeId: item.inLatticeId,
            inLatticeGoodsNum: item.inLatticeGoodsNum,
            goodsBatchId: item.goodsBatchId,
            goodsId: item.goodsId,
            goodsNum: item.goodsNum,
          };
        }),
      };
      this.subLoading = true
      shiftAdd(params).then((res) => {
        if (res.success) {
          this.$toast("移仓单创建成功！");
          this.initData()
        } else {
          this.$toast(res.message);
        }
      }).finally(() => {
        this.subLoading = false
      })
    },
    // 初始化页面数据
    initData() {
      let id = this.$route.query.id;
      this.resetForm()

      this.buildForm.docDate = recTime;
      // 获取当前用户 设定为提交人参数
      let currentLoginUser = JSON.parse(
        localStorage.getItem("pro__Login_Userinfo")
      ).value;

      // 获取移仓单类型
      getDictItemsByTypes({ type: 3 }).then((res) => {
        if (res.code == 200 && res.result) {
          this.warehousingTypes = res.result;
        }
      });

      if (id) {
        this.isEdit = true;
        this.appTitle = "编辑移仓单";
        // 移仓单详情 基本信息
        inboundTaskDetail({ taskId: id }).then((res) => {
          if (res.code == 200 && res.result) {
            let { id, code, type, sourceNumber } = res.result;
            this.buildForm = {
              id: id || "",
              sourceNumber: sourceNumber || "",
              code: code || "",
              type: type || "",
              applyUserId: currentLoginUser.id,
            };
          } else {
            this.$toast(res.message);
          }
        });
        // 移仓单详情 移仓明细
        inboundTaskDetailGoodsList({ taskId: id }).then((res) => {
          if (res.code == 200 && res.result) {
            this.getCheckedGoods(res.result.records);
          } else {
            this.$toast(res.message);
          }
        });
      } else {
        this.isEdit = false;
        this.appTitle = "新建移仓单";
        // 生产移仓单编号
        genEntityCode({ entityCode: "WMS_WAREHOUSE_SHIFT" }).then((res) => {
          if (res.code == 200) {
            this.buildForm.code = res.result;
          } else {
            this.buildForm.code = "";
            this.$toast(res.message);
          }
        });
      }
    },
    // 点击库位选择
    showLatticeNotification(index, item, flag) {
      this.recentGoodsIndex = index;
      this.goodParam = {
        batchCode: item.batchCode,
        goodsId: item.goodsId,
      };
      this.appTitle = "库位";
      if (flag == "in") {
        this.isShowInLattice = true;
      } else {
        this.latticeNotificationOutUrl = `/wmslattice/getLatticeNotificationForOutBound?batchCode=${item.batchCode}&goodsId=${item.goodsId}`; //移出库位的url
        this.isShowOutLattice = true;
      }
    },
    // 确认选中入库库位 多选
    async getCheckedValue(list) {
      if (this.recentLatIndex != -1) {
        return;
      }
      this.isShowInLattice = false;
      this.appTitle = "新建移仓单";

      this.entryDetails[this.recentGoodsIndex]["inLatticeDtoList"] = list.map(
        (son) => {
          let recIndex = this.entryDetails[this.recentGoodsIndex][
            "inLatticeDtoList"
          ].findIndex((ele) => ele.latticeId == son.id);

          if (recIndex != -1) {
            let recObj = this.entryDetails[this.recentGoodsIndex][
              "inLatticeDtoList"
            ][recIndex];
            return recObj;
          } else {
            let { id, latticeCode, latticeName } = son;
            return {
              latticeId: id,
              latticeCode: latticeCode,
              latticeName: latticeName,
              latticeInfo: latticeCode + "|" + latticeName,
              goodsNum: "",
            };
          }
        }
      );
    },
    // 确认选中入库库位 单选
    async handleList(binLocationid, item, text) {
      let currentItem = this.entryDetails[this.recentGoodsIndex]; //当前列
      if (binLocationid == currentItem.outLatticeId) {
        this.$toast("同一明细移出库位不能和移入库位相同,请重新选择！");
        this.isShowInLattice = false;
        return;
      }
      this.isShowInLattice = false;
      this.appTitle = "新建移仓单";
      let { id, latticeCode, latticeName } = item;
      this.entryDetails[this.recentGoodsIndex].inLatticeId = id;
      let len = this.entryDetails.filter(
        (i) =>
          i.goodsCode == currentItem.goodsCode &&
          i.batchCode == currentItem.batchCode &&
          i.inLatticeId == currentItem.inLatticeId &&
          i.outLatticeId == currentItem.outLatticeId
      ).length;
      // 判断移出库位、移入库位、物品、批号的组合不能重复
      if (len > 1) {
        this.entryDetails[this.recentGoodsIndex].inLatticeId = "";
        this.$toast("移出库位、移入库位、物品、批号的组合不能重复");
        return;
      }
      this.entryDetails[this.recentGoodsIndex].latticeInfo =
        latticeCode + "|" + latticeName;
      let number = await this.getLatticeNumber(latticeCode);
      this.entryDetails[this.recentGoodsIndex].inLatticeGoodsNum = number;
    },
    // 确认选中出库库位 单选
    async handleOutList(binLocationid, item, text) {
      let currentItem = this.entryDetails[this.recentGoodsIndex]; //当前列
      if (binLocationid == currentItem.inLatticeId) {
        this.$toast("同一明细移出库位不能和移入库位相同，请重新选择！");
        this.isShowOutLattice = false;
        return;
      }
      this.isShowOutLattice = false;
      this.appTitle = "新建移仓单";

      let { id, latticeCode, latticeName } = item;
      this.entryDetails[this.recentGoodsIndex].outLatticeId = id;
      let len = this.entryDetails.filter(
        (i) =>
          i.goodsCode == currentItem.goodsCode &&
          i.batchCode == currentItem.batchCode &&
          i.inLatticeId == currentItem.inLatticeId &&
          i.outLatticeId == currentItem.outLatticeId
      ).length;
      // 判断移出库位、移入库位、物品、批号的组合不能重复
      if (len > 1) {
        this.entryDetails[this.recentGoodsIndex].outLatticeId = "";
        this.$toast("移出库位、移入库位、物品、批号的组合不能重复");
        return;
      }
      this.entryDetails[this.recentGoodsIndex].latticeOutInfo =
        latticeCode + "|" + latticeName;
      let number = await this.getLatticeNumber(latticeCode);
      this.entryDetails[this.recentGoodsIndex].outLatticeGoodsNum = number;
      if (this.entryDetails[this.recentGoodsIndex].goodsNum) {
        let isTrue = this.entryDetails[this.recentGoodsIndex].goodsNum > number;
        if (isTrue) {
          this.entryDetails[this.recentGoodsIndex].goodsNum = "";
        }
      }
    },
    // 选中库位后，获取库存数量
    async getLatticeNumber(code) {
      let res = await getLatticeNotificationForOutBound({
        latticeCode: code,
        ...this.goodParam,
      });
      let { records: list } = res.result;
      let goodsNumTxt = 0;
      if (list.length) {
        goodsNumTxt = list[0].goodsNum;
      }

      return goodsNumTxt;
    },

    // 入库移仓明细 - 添加
    addInventoryGoods() {
      this.appTitle = "选择物品";
      this.showGoodsPicker = true;
    },
    // 入库移仓明细 - 删除
    deleteGoods(i) {
      this.entryDetails.splice(i, 1);
    },
    // 扫码相关
    // 打开相机
    clickCode(index, cIndex, isshow) {
      this.goodParam = {
        batchCode: cIndex.batchCode,
        goodsId: cIndex.goodsId,
      };
      let that = this;
      this.recentGoodsIndex = index;
      this.recentLatIndex = cIndex;
      this.isshow = isshow; //我用作标记是入库还是出库
      let platform = localStorage.getItem("currentEnvironment");
      switch (platform) {
        case "iwork":
          var opt = {
            success: function(res) {
              console.log(JSON.stringify(res), "APP扫码数据");
              if (res.retCode == 0) {
                that.onDecode(res.retData);
              } else {
                that.$toast(res.retMsg);
              }
            },
            fail: function(err) {
              that.$toast("扫码失败！");
            },
          };
          //插件调用代码
          WorkHelper.scan(opt);
          break;
        case "browser":
          // camera:: 'front'--前摄像头，'rear'后摄像头，'off'关闭摄像头，会获取最后一帧显示，'auto'开始获取摄像头
          that.codeForm.qrcode = true;
          that.camera = "rear";
          break;
        case "dingding":
          dd.biz.util.scan({
            type: "qrCode", // type 为 all、qrCode、barCode，默认是all。
            onSuccess: function(data) {
              //onSuccess将在扫码成功之后回调
              that.onDecode(data.text);
            },
            onFail: function(err) {
              // console.error(err,'error')
            },
          });
          break;
        default:
          "";
          break;
      }
    },
    // 扫码结果回调
    onDecode(result) {
      console.log("this.isshow", this.isshow);
      // result, 扫描结果，可以根据自己的需求来实现相应的功能
      this.codeForm.code = JSON.parse(result);
      if (this.codeForm.code.EntityType == "lattice" && this.codeForm.code.id) {
        // 库位二维码
        getWarehouseLatticeDetail(this.codeForm.code.id).then((res) => {
          if (res.code == 200 && res.result) {
            if (res.result.status == "effective") {
              let paramsId = res.result.id;
              this.goodsRemoveLattice = res.result; //库位信息
              if (this.isshow == "out") {
                this.handleOutList(res.result.id, res.result);
                this.turnCameraOff();
              }
              if (this.isshow == "in") {
                this.handleList(res.result.id, res.result);
                this.turnCameraOff();
              }
              if (this.isshow == "batch") {
                getLatticeInfoForScan({
                  id: paramsId,
                  scope: "Inventory_move",
                }).then((res) => {
                  if (res.success) {
                    this.goodsRemoveData = res.result;
                    this.turnCameraOff();
                    this.appTitle = "移出库位物品";
                    this.showGoodsRemovePicker = true;
                  } else {
                    this.$toast(res.message);
                    this.turnCameraOff();
                  }
                });
              }
            } else {
              this.$toast("该库位已被禁用");
              this.clickCode(this.recentGoodsIndex);
            }
          } else {
            this.$toast(res.message);
            this.turnCameraOff();
          }
        });
      } else {
        this.$toast("请扫正确二维码");
        this.clickCode(this.recentGoodsIndex);
      }
    },
    // 相机反转
    switchCamera() {
      switch (this.camera) {
        case "front":
          this.camera = "rear";
          break;
        case "rear":
          this.camera = "front";
          break;
        default:
          this.$toast("错误");
      }
    },
    // 关闭相机
    turnCameraOff() {
      this.camera = "off";
      this.codeForm.qrcode = false;
    },
    // 打开手电筒
    ClickFlash() {
      switch (this.torchActive) {
        case true:
          this.torchActive = false;
          break;
        case false:
          this.torchActive = true;
          break;
        default:
          this.$toast("错误");
      }
    },
    // 检查是否调用摄像头
    async onInit(promise) {
      try {
        await promise;
      } catch (error) {
        if (error.name === "StreamApiNotSupportedError") {
        } else if (error.name === "NotAllowedError") {
          this.errorMessage = "Hey! I need access to your camera";
        } else if (error.name === "NotFoundError") {
          this.errorMessage = "Do you even have a camera on your device?";
        } else if (error.name === "NotSupportedError") {
          this.errorMessage =
            "Seems like this page is served in non-secure context (HTTPS, localhost or file://)";
        } else if (error.name === "NotReadableError") {
          this.errorMessage =
            "Couldn't access your camera. Is it already in use?";
        } else if (error.name === "OverconstrainedError") {
          this.errorMessage =
            "Constraints don't match any installed camera. Did you asked for the front camera although there is none?";
        } else {
          this.errorMessage = "UNKNOWN ERROR: " + error.message;
        }
      }
    },
    // 激光扫码
    changeScan(v) {
      if (v.EntityType == "goods") {
        getWarehouseLatticeDetail(v.id).then((res) => {
          if (res.code == 200 && res.result) {
            let paramsId = res.result.id;
            this.goodsRemoveLattice = res.result; //库位信息
            getLatticeInfoForScan({
              id: paramsId,
              scope: "Inventory_move",
            }).then((res) => {
              if (res.success) {
                this.goodsRemoveData = res.result;
                this.turnCameraOff();
                this.appTitle = "移出库位物品";
                this.showGoodsRemovePicker = true;
              } else {
                this.$toast(res.message);
                this.turnCameraOff();
              }
            });
          } else {
            this.turnCameraOff();
            this.$toast(res.message);
          }
          return;
          if (res.code == 200 && res.result) {
            if (res.result.status == "effective") {
              let { id, latticeCode, latticeName } = res.result;
              let recLatIndex = this.entryDetails[this.active][
                "inLatticeDtoList"
              ].findIndex((ele) => ele.latticeId == id);
              if (recLatIndex == -1) {
                let obj = {
                  latticeId: id,
                  latticeCode: latticeCode,
                  latticeName: latticeName,
                  latticeInfo: latticeCode + "|" + latticeName,
                  goodsNum: "",
                };
                this.entryDetails[this.active]["inLatticeDtoList"].push(obj);
              } else {
                this.$toast("该库位已存在");
              }
            } else {
              this.$toast("该库位处于禁用状态");
            }
          } else {
            this.$toast("数据异常");
          }
        });
      }
    },
    // 确认选中物品 物品可复选
    async getCheckedGoods(list) {
      this.showGoodsPicker = false;
      this.appTitle = "新建移仓单";

      let newbatchCode = recTime.replace(/\-/g,"").substring(2)

      let checkedGoods = list.map((son) => {
        let {
          id,
          goodsId,
          goodsCode,
          goodsName,
          spec,
          address,
          packageSpec,
          unitIdText,
          unitName,
          batchCode,
          goodsBatchId,
          produceDate,
          goodsNum,
        } = son;
        return {
          id: id || "",
          goodsKey: goodsId || id + "_" + Math.floor(Math.random() * 1000),
          goodsId: goodsId || "",
          goodsCode: goodsCode || "-",
          goodsName: goodsName || "-",
          spec: spec || "-",
          address: address || "-",
          packageSpec: packageSpec || "-",
          unitName: unitIdText || unitName || "-",
          batchCode: batchCode || newbatchCode,
          goodsBatchId: goodsBatchId || "",
          produceDate: produceDate || recTime,
          goodsNum: goodsNum || "",
        };
      });

      this.entryDetails = this.entryDetails.concat(checkedGoods);

      // this.entryDetails.forEach((ele) => {
      //   let { goodsId, batchCode } = ele;
      //   getBathRelProductDate({ goodsId, batchCode }).then((res) => {
      //     if (res.code == 200 && res.result) {
      //       ele.goodsBatchId = res.result.id;
      //     } else {
      //       ele.goodsBatchId = "";
      //     }
      //   });
      // });
    },
    // 确认选中物品 移出库位的物品  可复选
    async getCheckedGoodsRemove(list) {
      console.log("list", list);
      this.showGoodsRemovePicker = false;
      this.appTitle = "新建移仓单";

      let newbatchCode = recTime.replace(/\-/g,"").substring(2)

      let checkedGoods = list.map((son) => {
        let {
          id,
          goodsId,
          goodsCode,
          goodsName,
          spec,
          address,
          packageSpec,
          unitIdText,
          unitName,
          batchCode,
          goodsBatchId,
          produceDate,
          goodsNum,
        } = son;
        return {
          id: id || "",
          goodsKey: goodsId || id + "_" + Math.floor(Math.random() * 1000),
          goodsId: goodsId || "",
          goodsCode: goodsCode || "-",
          goodsName: goodsName || "-",
          spec: spec || "-",
          address: address || "-",
          packageSpec: packageSpec || "-",
          unitName: unitIdText || unitName || "-",
          batchCode: batchCode || newbatchCode,
          goodsBatchId: goodsBatchId || "",
          produceDate: produceDate || recTime,
          goodsNum: goodsNum || "",
          outLatticeId: this.goodsRemoveLattice.id,
          latticeOutInfo:
            this.goodsRemoveLattice.latticeCode +
            "|" +
            this.goodsRemoveLattice.latticeName,
        };
      });

      this.entryDetails = this.entryDetails.concat(checkedGoods);

      // this.entryDetails.forEach((ele) => {
      //   let { goodsId, batchCode } = ele;
      //   getBathRelProductDate({ goodsId, batchCode }).then((res) => {
      //     if (res.code == 200 && res.result) {
      //       ele.goodsBatchId = res.result.id;
      //     } else {
      //       ele.goodsBatchId = "";
      //     }
      //   });
      // });
    },
    // 移仓单 移仓明细 数量处理
    needInNumChange(e, item) {
      let value = this.clearNoNum(e);
      if (value > item.outLatticeGoodsNum) {
        this.$toast("输入数量不能大于移出库位库存");
        return "";
      }
      return value;
    },
    /*数量处理*/
    clearNoNum(value) {
      //先把非数字的都替换掉，除了数字和.
      value = value.replace(/[^\d.]/g, "");
      //保证只有出现一个.而没有多个.
      value = value.replace(/\.{2,}/g, ".");
      //必须保证第一个为数字而不是.
      value = value.replace(/^\./g, "");
      //保证.只出现一次，而不能出现两次以上
      value = value
        .replace(".", "$#$")
        .replace(/\./g, "")
        .replace("$#$", ".");
      //只能输入四个小数
      value = value.replace(/^(\-)*(\d+)\.(\d\d\d\d).*$/, "$1$2.$3");
      // console.log(value.includes('.'),'wwwwww')
      //小数位处理
      if (value.substring(0, 1) == "0" && value.substring(0, 2) != "0.") {
        value = "0";
      }
      //输入长度控制
      if (value > 99999999999999.9999) {
        value = "";
      }
      return value;
    },
    // 打开选择时间
    openTimePicker(index, value) {
      this.timePickShow = true;
    },
    // 确定选择时间
    confirmPick(date) {
      this.buildForm.docDate = moment(date).format("YYYY-MM-DD");
      this.timePickShow = false;
    },
    // 取消选择时间
    cancelPick() {
      this.timePickShow = false;
    },
    formatter(type, val) {
      if (type === "year") {
        return val + "年";
      }
      if (type === "month") {
        return val + "月";
      }
      if (type === "day") {
        return val + "日";
      }
      return val;
    },
    // 验证数组内是否存在相同对象
    hasDuplicateObjects(arr) {
      for (let i = 0; i < arr.length - 1; i++) {
        for (let j = i + 1; j < arr.length; j++) {
          if (this.isEqual(arr[i], arr[j]) > -1) {
            return this.isEqual(arr[i], arr[j]); // 存在重复对象
          }
        }
      }
      return -1; // 不存在重复对象
    },
    isEqual(obj1, obj2) {
      if (obj1["goodsId"] == obj2["goodsId"]) {
        if (obj1["batchCode"] == obj2["batchCode"]) {
          let recIndex = this.entryDetails.findIndex(
            (ele) =>
              ele.inLatticeId == obj1["inLatticeId"] &&
              ele.outLatticeId == obj1["outLatticeId"]
          );
          return recIndex;
        } else {
          return -1;
        }
      } else {
        return -1;
      }
    },
  },
};
</script>
<style lang="scss" scoped>
@import "@/assets/theme.scss";
@import "@/views/workManagement/materialRequisition/materialForm.scss";
.form-content {
  width: 100%;
  height: calc(100vh - 203px);
  background: #f5f5f5;
  overflow: scroll;
  padding: 20px 0;
  .formgroup {
    background: #ffffff;
    margin-top: 0.1rem;
    margin-bottom: 0.2rem;
    padding-top: 0.1rem;

    .title {
      width: 0.58rem;
      height: 0.14rem;
      font-size: 0.15rem;
      font-family: PingFang SC;
      font-weight: 400;
      color: #191f25;
      line-height: 0.05rem;
      margin-left: 0.16rem;
    }
  }
  .search-bottoms {
    width: 100%;
    height: 100px;
    background: #ffffff;
    display: flex;
    justify-content: space-between;
    align-items: center;
    position: fixed;
    bottom: 0px;
    padding: 0rem 11px;
    box-sizing: border-box;
    font-size: 32px;
    font-weight: 500;
    z-index: 9;
    .btnconfirm {
      flex: 1;
      background: #1890ff;
      box-sizing: border-box;
      height: 78px;
      display: flex;
      justify-content: center;
      align-items: center;
      border-radius: 6px;
      color: #ffffff;
    }
  }
}
.bottomLine {
  height: 1px;
  background-color: #f2f2f2;
  margin: 0 2px;
}
.haveUnitBox {
  display: flex;
  justify-content: space-between;
  align-items: center;
  box-sizing: border-box;
  padding-right: 32px;
  /deep/ .van-cell {
    padding-right: 0;
    width: 600px;
  }
  /deep/ .van-field__control {
    max-width: 700px;
    // text-align: right;
  }
}
/deep/ .van-nav-bar {
  z-index: 99;
}
/deep/.van-sidebar-item--select::before {
  color: #1890ff;
  background-color: #1890ff;
}
/deep/.van-tree-select__item--active {
  color: #1890ff;
}
.addGoodScontain {
  display: flex;
  flex-wrap: nowrap;
  .addgoods {
    flex: 1;
    background: #fff;
    font-size: 32px;
    text-align: center;
    height: 78px;
    line-height: 78px;
    color: #1890ff;
  }
}
.required span::after {
  left: -20px;
  top: 3px;
}
.filedClear {
  width: 28px;
  height: 28px;
}
.formItemFlex {
  display: flex;
  flex-direction: row;
  .FormTit {
    flex: 1;
    min-width: 3.3rem;
    padding-top: 0.33rem;
  }
  .haveUnitBox {
    flex: 1;
    .van-cell {
      width: 6.2rem;
    }
  }
}
.list {
  margin-top: 10px;
  .wrap {
    background: #fff;
    margin-top: 20px;
    width: 100vw;
    .otherText {
      display: flex;
      justify-content: space-between;
      font-size: 32px;
      font-weight: bold;
      color: #191f25;
      .deleteStyle {
        font-weight: 400;
        color: #ff4d4f;
      }
    }
    .top {
      display: flex;
      justify-content: flex-start;
      padding-top: 10px;
      .icon {
        width: 6px;
        height: 32px;
        background: #1890ff;
        margin: 6px 10px 0 10px;
      }
      .title {
        width: 602px;
        margin-right: 20px;
        font-size: 30px;
        font-family: PingFang SC;
        font-weight: 400;
        color: #191f25;
        overflow: hidden;
        text-overflow: ellipsis;
        white-space: nowrap;
      }
      .titleWidth {
        width: 572px;
      }
    }
    .center {
      p {
        margin: 16px 25px;
        font-size: 28px;
        display: flex;
        position: relative;
        .key {
          color: #888888;
        }
        .value {
          color: #191f25;
          width: 380px;
          display: block;
          overflow: hidden;
          text-overflow: ellipsis;
          white-space: nowrap;
        }
        .arrow {
          color: #1890ff;
          position: absolute;
          right: -10px;
        }
      }
      .showAll {
        background: #f5f8ff;
        width: 100vw;
        margin-left: -30px;
        padding: 30px;
        margin-bottom: 30px;
      }
      .showAll2 {
        width: 100%;
        margin: 0 0 30px 0;
        padding: 30px 0;
      }
    }
  }
}
.label-list {
  margin-left: -6px;
  margin-top: -20px;
  span {
    height: 0.62667rem;
    background: #f0f6fe;
    color: #1890ff !important;
    margin-right: 20px;
    padding: 6px 16px;
    font-size: 22px;
    border-radius: 6px;
  }
}
</style>
